import logging
import sys
from sqlalchemy_utils import database_exists, create_database
from sqlalchemy import inspect, text
from dotenv import load_dotenv
import os

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

# 加载环境变量
load_dotenv()

# 导入模型
from models.base import Base, engine
from models.user import User
from models.item import Item
from models.user_api_key import UserApiKey
from models.kline_5min import Kline5Min
from models.strategy_config import StrategyConfig

# Import all models here so that they are registered with SQLAlchemy's metadata
from models import user, item, kline_5min, contract, strategy, user_api_key, strategy_config

def init_db():
    """初始化数据库和创建表"""
    try:
        # 获取数据库连接URL
        db_url = str(engine.url)
        db_name = db_url.split("/")[-1].split("?")[0]
        logger.info(f"数据库URL: {db_url}")
        
        # 检查数据库是否存在，如果不存在则创建
        if not database_exists(engine.url):
            logger.info(f"数据库 {db_name} 不存在，正在创建...")
            create_database(engine.url)
            logger.info(f"数据库 {db_name} 创建成功")
        else:
            logger.info(f"数据库 {db_name} 已存在")
        
        # 连接数据库
        with engine.connect() as conn:
            logger.info("数据库连接成功")
            
            # 检查数据库版本
            if 'mysql' in db_url:
                result = conn.execute(text("SELECT VERSION()"))
                version = result.scalar()
                logger.info(f"MySQL版本: {version}")
        
        # 获取所有表名
        inspector = inspect(engine)
        existing_tables = inspector.get_table_names()
        logger.info(f"现有表: {', '.join(existing_tables) if existing_tables else '无'}")
        
        # 获取要创建的表
        tables_to_create = Base.metadata.tables.keys()
        logger.info(f"要创建的表: {', '.join(tables_to_create)}")
        
        # 创建表
        Base.metadata.create_all(bind=engine)
        logger.info("表创建完成")
        
        # 验证表是否创建成功
        inspector = inspect(engine)
        created_tables = inspector.get_table_names()
        logger.info(f"创建后的表: {', '.join(created_tables)}")
        
        # 检查是否所有表都创建成功
        missing_tables = [table for table in tables_to_create if table not in created_tables]
        if missing_tables:
            logger.warning(f"以下表未成功创建: {', '.join(missing_tables)}")
        else:
            logger.info("所有表都已成功创建")
            
        # 检查每个表的列
        for table in created_tables:
            columns = [column['name'] for column in inspector.get_columns(table)]
            logger.info(f"表 {table} 的列: {', '.join(columns)}")
            
    except Exception as e:
        logger.error(f"初始化数据库时出错: {e}", exc_info=True)
        raise

if __name__ == "__main__":
    logger.info("开始初始化数据库...")
    init_db()
    logger.info("数据库初始化完成") 